from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics

from goods.models import SKU
from .models import User,Address
from . import serializers
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import ModelViewSet
from . import constants
from django_redis import get_redis_connection
from goods.serializers import SKUListSerializer
from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_to_redis

class UsernameCountView(APIView):
    '''
    查询用户是否存在
    '''
    def get(self,request,username):
        #统计用户名个数
        count=User.objects.filter(username=username).count()
        #响应
        return Response({
            'username':username,
            'count':count
        })


class MobileCountView(APIView):
    def get(self,request,mobile):
        count=User.objects.filter(mobile=mobile).count()
        return Response({
            'mobile':mobile,
            'count':count
        })



class RegisterView(generics.CreateAPIView):
    '''
    注册：创建新用户对象

    '''
    #指定查询及，当前值实现创建功能，不需要查询，可以不指定
    #值序列化器，验证接受的数据，创建

    serializer_class = serializers.UserRegisterSerializer



class UserView(generics.RetrieveAPIView):

    #需要登录
    permission_classes = [IsAuthenticated]

    serializer_class = serializers.UserSerializer
    #不需要查询，而是获取当前登录的用户
    # queryset = User.objects.all()
    #重写方法，不跟据主键查询而是聪jwt中获取
    def get_object(self):
        return self.request.user



class EmailView(generics.UpdateAPIView):
    #根据主键查询属性，在进行修改
    serializer_class = serializers.UserEmailSerializer

    #访问此时图时需要先登录
    permission_classes = [IsAuthenticated]

    #获取当前登录的用户对象而不是进行查询
    def get_object(self):
        return self.request.user


class EmailActiveView(APIView):
    def get(self,request):
        #1.接受加密信息
        token=request.query_params.get('token')
        #2.解密验证
        user = User.email_loads(token)
        if user is None:
            return Response({'message':'激活链接无效'})
        #3.查询用户对象，修改属性
        user.email_active = True
        user.save()

        #响应
        return Response({'message': '激活成功'})



class AddressViewSet(ModelViewSet):
    permission_classes = [IsAuthenticated]

    #查询当前登录用户的收获地址
    def get_queryset(self):
        #获取当前登录用户
        user = self.request.user

        #获取这个用户的所有收获地址
        return user.addresses.filter(is_deleted=False)
    serializer_class = serializers.AddressSerializer

    def list(self, request, *args, **kwargs):
        user = request.user
        address_list = self.get_queryset()
        serializer = serializers.AddressSerializer(address_list,many=True)

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })
    def destroy(self, request, *args, **kwargs):
        #逻辑删除
        address=self.get_queryset()
        address.is_deleted=True
        address.save()
        return Response(status=204)

    #定义新的方法，修改地址的标题
    @action(methods=['put'],detail=True)
    def title(self,request,pk):
        #1.查询收获地址对象
        try:
            address = Address.objects.get(pk=pk)
        except:
            return Response({'message':'编号无效'})
        #2.接受收获地址
        title_dict = request.data
        #3.验证，修改
        serializer=serializers.TitleSerializer(address,data=title_dict)
        serializer.is_valid(raise_exception=True)
        address=serializer.save()
        #4.响应
        return Response({
            'id':address.id,
            'title':address.title,
        })

    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        #设置默认收获地址
        user=request.user
        user.default_address_id=pk
        user.save()
        return Response({'message':'OK'})

class HistoryView(generics.CreateAPIView):
    #创建，不需要指定查询集，只指定序列化器
    permission_classes = [IsAuthenticated]
    serializer_class = serializers.HistorySerializer

    def get(self,request):
        #1.读取redis中浏览记录
        redis_cli = get_redis_connection('history')
        sku_ids = redis_cli.lrange('history_%d' % request.user.id,0,-1)
        #2.查询商品对象
        skus = []
        for sku_id in sku_ids:
            skus.append(SKU.objects.get(pk=sku_id))
        #3.序列化输出
        serializer = SKUListSerializer(skus,many=True)
        return Response(serializer.data)


class AuthenticationView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response = super().post(request,*args,**kwargs)

        #在原有的登录逻辑基础上，添加自己的逻辑代码
        if 'user_id' in response.data:
            user = User.objects.get(pk=response.data.get('user_id'))
            response = merge_cookie_to_redis(request,user,response)

        return response
